package structure;

/**
 * 通过链表实现栈
 */
public class Stack {

    private Node top;
    private int size;

    public Stack() {
    }

    /**
     * 入栈
     * @param value
     */
    public void push(Object value){
        Node pushedNode = new Node(value);
        pushedNode.next = top;
        top = pushedNode;

        size++;
    }

    /**
     * 出栈
     */
    public Object pop() throws Exception {

        if(size == 0){
            throw new Exception("空栈异常");
        }

        Node popedNode = top;
        top = top.next;
        size --;

        return  popedNode.data;
    }

    /**
     * 遍历栈
     */
    public void traverse(){
        Node temp = top;
        while (temp != null){
            System.out.println(""+temp.data);

            temp = temp.next;

        }
    }

    /**
     * 返回栈顶元素
     */
    public Object peek() throws Exception {
        if(size == 0){
            throw new Exception("空栈异常");
        }

        return  top.data;
    }

    /**
     * 返回栈的大小
     * @return
     */
    public int getSize(){
        return  this.size;
    }
}
